package com.rayboot.footpoint.provider;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

import com.rayboot.footpoint.utils.StorageUtil;
import com.rayboot.footpoint.utils.Util;

public class FootpointContentProvider extends ContentProvider {
	public static final String AUTGIRUTIES = "com.rayboot.footpoint.provider.FootprintContentProvider";
	public static final String DATABASE_NAME = "footprints.db";
	public static final int DATABASE_VERSION = 36;
	private static final String TAG = "FootpointContentProvider";
	private Runnable copyDBToSDRunnable = new Runnable() {
		public void run() {
			Log.d(TAG, "db onChange sync to SD!");
			Util.touchSDFile();
			File file = new File(StorageUtil.getFootprintStorageDirectory()
					+ File.separator + DATABASE_NAME);
			Util.copyFile(
					new File(FootpointContentProvider.this.mDataBase.getPath()),
					file);
		}
	};
	private SQLiteDatabase mDataBase;
	private Handler mHandler;
	private HashMap<Uri, ISubProvider> mSubProviderMap = new HashMap();

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		ISubProvider localISubProvider = getISubProvider(uri);
		if (localISubProvider != null) {
			int count = localISubProvider.delete(uri, selection, selectionArgs);
			getContext().getContentResolver().notifyChange(uri, null);
			return count;
		}
		throw new IllegalArgumentException("Unknown URL " + uri);
	}

	@Override
	public String getType(Uri uri) {
		return getISubProvider(uri).getType(uri);
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		ISubProvider localISubProvider = getISubProvider(uri);
		if (localISubProvider != null) {
			Uri mUri = localISubProvider.insert(uri, values);
			getContext().getContentResolver().notifyChange(mUri, null);
			return mUri;
		}
		throw new IllegalArgumentException("Unknown URL " + uri);
	}

	@Override
	public boolean onCreate() {
		registerSubProvider(new CategoryProvider());
		registerSubProvider(new FootprintsProvider());
		this.mDataBase = new DatabaseHelper(getContext(), DATABASE_NAME, null,
				DATABASE_VERSION).getWritableDatabase();
		Iterator localIterator = this.mSubProviderMap.values().iterator();
		while (localIterator.hasNext()) {
			((ISubProvider) localIterator.next()).setDB(this.mDataBase);
		}
		this.mHandler = new Handler();

		// getContext().getContentResolver().registerContentObserver(FootprintsProvider.FootprintColumns.CONTENT_URI,
		// true, new ContentObserver( new Handler() ) {
		//
		//
		// })
		//
		//
		// getContext().getContentResolver().registerContentObserver(
		// FootprintsProvider.FootprintColumns.CONTENT_URI, true,
		// new ContentObserver(mHandler) {
		// public void onChange(boolean paramBoolean) {
		// if (!paramBoolean) {
		// FootpointContentProvider.this.mHandler
		// .removeCallbacks(FootpointContentProvider.this.copyDBToSDRunnable);
		// FootpointContentProvider.this.mHandler
		// .postDelayed(
		// FootpointContentProvider.this.copyDBToSDRunnable,
		// 500L);
		// }
		// }
		// });
		return mDataBase == null ? false : true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		ISubProvider localISubProvider = getISubProvider(uri);
		if (localISubProvider != null) {
			Cursor cursor = localISubProvider.query(uri, projection, selection,
					selectionArgs, sortOrder);
			cursor.setNotificationUri(getContext().getContentResolver(), uri);
			return cursor;
		}
		throw new IllegalArgumentException("Unknown URL " + uri);
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		ISubProvider localISubProvider = getISubProvider(uri);
		if (localISubProvider != null) {
			int i = localISubProvider.update(uri, values, selection,
					selectionArgs);
			getContext().getContentResolver().notifyChange(uri, null);
			return i;
		}
		throw new IllegalArgumentException("Unknown URL " + uri);
	}

	public ISubProvider getISubProvider(Uri paramUri) {
		String[] arrayOfString = paramUri.toString().split("/");
		if (arrayOfString.length > 3)
			;
		for (Uri localUri = Uri.parse(arrayOfString[0] + "//"
				+ arrayOfString[2] + "/" + arrayOfString[3]);; localUri = paramUri) {
			Log.d(TAG, localUri.toString());
			return (ISubProvider) this.mSubProviderMap.get(localUri);
		}
	}

	public void registerSubProvider(ISubProvider provider) {
		provider.setContext(getContext());
		this.mSubProviderMap.put(provider.getBaseURI(), provider);
	}

	private class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			Iterator localIterator = FootpointContentProvider.this.mSubProviderMap
					.values().iterator();
			while (localIterator.hasNext())
				((ISubProvider) localIterator.next()).onCreate(db);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub

		}

	}

}
